from uuid import uuid4
from django.utils.timezone import now

from rest_framework import serializers

from .models import Gateway, OneLineHistory
from util.exception import ValidationError
from django.conf import settings


class OnelineHistorySerializer(serializers.ModelSerializer):
    gateway_id = serializers.IntegerField(allow_null=False)
    is_connected = serializers.BooleanField(allow_null=False)

    def validate_gateway_id(self, obj):
        gateway = Gateway.objects.filter(gateway_id=obj).first()
        if not gateway:
            raise ValidationError(30002)
        return obj

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        data["key"] = id
        his_data = {}
        his_data["key"] = id
        his_data["gateway_id"] = data.get("gateway_id")
        his_data["is_connected"] = data.get("is_connected")
        OneLineHistory.objects.create(**his_data)
        gateway = Gateway.objects.filter(gateway_id=data.get("gateway_id")).first()
        gateway.last_log_in = now()
        gateway.state = data.get("is_connected")
        gateway.save()
        if gateway.is_tac31 and data.get("is_connected"):
            return gateway.gateway_id

    class Meta:
        model = OneLineHistory
        fields = ["gateway_id", "is_connected"]
